package com.apartment.own.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.apartment.common.annotation.Excel;
import com.apartment.common.utils.SecurityUtils;
import com.apartment.own.domain.*;
import com.apartment.own.domain.constant.ClassNameConstants;
import com.apartment.common.exception.CustomException;
import com.apartment.common.utils.DateUtils;
import com.apartment.own.domain.enums.ApprovalStatusEnum;
import com.apartment.own.mapper.*;
import com.apartment.own.request.ord.ApproveDTO;
import com.apartment.own.request.ord.TenantContractDTO;
import com.apartment.own.response.ord.ApproveResp;
import com.apartment.own.service.IOwnResPropertyFeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.apartment.own.service.IOwnOrdTenantContractService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 租客合同Service业务层处理
 *
 * @author @Dog_E
 * @date 2020-08-28
 */
@Service
public class OwnOrdTenantContractServiceImpl extends ServiceImpl<OwnOrdTenantContractMapper, OwnOrdTenantContract> implements IOwnOrdTenantContractService {
    @Autowired
    private OwnOrdTenantContractMapper ownOrdTenantContractMapper;
    @Autowired
    private OwnOuResidentMapper ownOuResidentMapper;
    @Autowired
    private OwnOrdCashPledgeMapper cashPledgeMapper;
    @Autowired
    private OwnResArticleInventoryMapper resArticleInventoryMapper;
    @Autowired
    private IOwnResPropertyFeeService resPropertyFeeService;

    /**
     * 查询租客合同
     *
     * @param id 租客合同ID
     * @return 租客合同
     */
    @Override
    public OwnOrdTenantContract selectOwnOrdTenantContractById(Long id) {
        return ownOrdTenantContractMapper.selectOwnOrdTenantContractById(id);
    }

    /**
     * 查询租客合同列表
     *
     * @param ownOrdTenantContract 租客合同
     * @return 租客合同
     */
    @Override
    public List<OwnOrdTenantContract> selectOwnOrdTenantContractList(OwnOrdTenantContract ownOrdTenantContract) {
        return ownOrdTenantContractMapper.selectOwnOrdTenantContractList(ownOrdTenantContract);
    }

    /**
     * 新增租客合同
     *
     * @param ownOrdTenantContract 租客合同
     * @return 结果
     */
    @Override
    public int insertOwnOrdTenantContract(OwnOrdTenantContract ownOrdTenantContract) {
        ownOrdTenantContract.setCreateTime(DateUtils.getNowDate());
        return ownOrdTenantContractMapper.insertOwnOrdTenantContract(ownOrdTenantContract);
    }

    /**
     * 修改租客合同
     *
     * @param ownOrdTenantContract 租客合同
     * @return 结果
     */
    @Override
    public int updateOwnOrdTenantContract(OwnOrdTenantContract ownOrdTenantContract) {
        ownOrdTenantContract.setUpdateTime(DateUtils.getNowDate());
        return ownOrdTenantContractMapper.updateOwnOrdTenantContract(ownOrdTenantContract);
    }

    /**
     * 批量删除租客合同
     *
     * @param ids 需要删除的租客合同ID
     * @return 结果
     */
    @Override
    public int deleteOwnOrdTenantContractByIds(Long[] ids) {
        return ownOrdTenantContractMapper.deleteOwnOrdTenantContractByIds(ids);
    }

    /**
     * 删除租客合同信息
     *
     * @param id 租客合同ID
     * @return 结果
     */
    @Override
    public int deleteOwnOrdTenantContractById(Long id) {
        return ownOrdTenantContractMapper.deleteOwnOrdTenantContractById(id);
    }


    /**
     * @param contractDTO: 添加租客合同DTO
     * @Description: 添加租客合同
     * @return: int
     * @Author: @Dog_E
     * @Date: 2020/8/31 0031
     **/
    @Override
    @Transactional()
    public int insertTenantContract(TenantContractDTO contractDTO) {
        //1.添加租赁合同
        //1.添加到审批状态
        //1.1更改合同为待审批状态
        //添加房源
        contractDTO.setCreateTime(new Date());//添加添加时间
        contractDTO.setCreateBy(SecurityUtils.getUser().getUserId().toString());//添加添加人
        if (Objects.isNull(contractDTO.getHouseId())) {
            throw new CustomException("房源不能为空");
        }
        if (Objects.isNull(contractDTO.getStartLeaseTime())||Objects.isNull(contractDTO.getSurrenderLeaseTime())) {
            throw new CustomException("起租退租不能为空");
        }
        if (Objects.isNull(contractDTO.getTel())) {
            throw new CustomException("手机号不能为空");
        }
        if (Objects.isNull(contractDTO.getName())) {
            throw new CustomException("租住人名字不能为空");
        }
        if (Objects.isNull(contractDTO.getMonthlyRent())) {
            throw new CustomException("月租金不能为空");
        }
        contractDTO.setApprovalStatus(ApprovalStatusEnum.PENDING.getId().toString());
        int i = ownOrdTenantContractMapper.insertOwnOrdTenantContract(contractDTO);
        //TODO 发送短信验证码
        //TODO 添加账单
        //TODO 添加
        //2.获取入住人集合
        List<OwnOuResident> resident = contractDTO.getResident();
        if (Objects.nonNull(resident)) {
            resident.forEach(r -> {
                if (r.getName() == null || "".equals(r.getName())) {
                    throw new CustomException("入住人名字不能为空", 500);
                }
                //设置关系标识
                r.setForeignId(contractDTO.getId());//外键(不唯一)
                r.setSurfaceName(ClassNameConstants.OU_RESIDENT_FK_ORD_TENANT_CONTRACT);//关系
                //添加入住人
                ownOuResidentMapper.insertOwnOuResident(r);
            });
        }

        //3.获取押金集合
        List<OwnOrdCashPledge> cashPledge = contractDTO.getCashPledge();
        if (Objects.nonNull(cashPledge)) {
            cashPledge.forEach(c -> {
                if (c.getCashPledgeType() == null) {
                    throw new CustomException("缺少押金类型", 500);
                }
                if (c.getCost() == null) {
                    throw new CustomException("押金不能为空", 500);
                }
                //外键(不唯一)
                c.setForeignId(contractDTO.getId());
                //设置关系标识
                c.setSurfaceName(ClassNameConstants.OU_RESIDENT_FK_ORD_TENANT_CONTRACT);//关系
                cashPledgeMapper.insertOwnOrdCashPledge(c);
            });
        }

        //4.获取合同物品集合
        List<OwnResArticleInventory> contractItems = contractDTO.getContractItems();
        if (!Objects.isNull(contractItems)) {
            contractItems.forEach(c -> {
                //判断物品数量是不是0
                if (!Objects.isNull(c.getQuantity())&&c.getQuantity() != 0L) {
                    //外键(不唯一)
                    c.setForeignId(contractDTO.getId());
                    //设置关系标识
                    c.setSurfaceName(ClassNameConstants.OU_RESIDENT_FK_ORD_TENANT_CONTRACT);//关系
                    resArticleInventoryMapper.insertOwnResArticleInventory(c);
                }
            });
        }
        //获取物业交割信息
        List<OwnResPropertyFee> resPropertyFees = contractDTO.getResPropertyFees();
        if (!Objects.isNull(resPropertyFees)) {
            resPropertyFees.forEach(propertyFees -> {
                //外键(不唯一)
                propertyFees.setForeignId(contractDTO.getId());
                //设置关系标识
                propertyFees.setSurfaceName(ClassNameConstants.ORD_TENANT_CONTRACT_FK_OWN_RES_PROPERTY_FEE);//关系
            });
            resPropertyFeeService.saveBatch(resPropertyFees);
        }


        //TODO 更改房源状态
        //账单
        return i;
    }

    /**
     * @Description: 审批查询
     * @param approveDTO: 审批请求体
     * @return: ApproveResp 返回审批对象
     * @Author: @Dog_E
     * @Date: 2020/9/15 0015 09:30
     **/
    @Override
    public List<ApproveResp> approvalQuery(ApproveDTO approveDTO){
        return ownOrdTenantContractMapper.approvalQuery(approveDTO);
    }
}
